import { ITransfer } from "../../../../../Core/Module/EventSystem/ITransfer";
import { IsInstanceOf } from "../../../../../Decorator/Decorator";
import { M2M_UnitTransferRequest, M2M_UnitTransferResponse } from "../../../../Model/Generate/Share/Message/InnerMessage_S_20001";
import { M2C_StartSceneChange } from "../../../../Model/Generate/Share/Message/OuterMessage_C_10001";
import { ActorMessageSenderComponent } from "../../../../Model/Server/Module/Actor/ActorMessageSenderComponent";
import { MailBoxComponent } from "../../../../Model/Server/Module/Actor/MailBoxComponent";
import { LocationProxyComponent } from "../../../../Model/Server/Module/ActorLocation/LocationProxyComponent";
import { Unit } from "../../../../Model/Share/Module/Unit/Unit";
import { BsonHelper } from "../../Module/Serialize/BsonHelper";
import { MessageHelper } from "../Helper/MessageHelper";

export class TransferHelper {

    public static async Transfer(unit: Unit, sceneInstanceId: number, sceneName: string) {
        // 通知客户端开始切场景
        const m2CStartSceneChange = new M2C_StartSceneChange();
        m2CStartSceneChange.SceneInstanceId = sceneInstanceId;
        m2CStartSceneChange.SceneName = sceneName;
        MessageHelper.SendToClient(unit, m2CStartSceneChange);

        console.log(`传送之前`);
        console.log(unit);

        const request = new M2M_UnitTransferRequest();
        request.Unit = BsonHelper.Serialize(unit);
        request.Entitys = [];
        for (let [, entity] of unit.components) {
            if (IsInstanceOf(entity, ITransfer)) {
                request.Entitys.push(BsonHelper.Serialize(entity));
            }
        }
        // 删除Mailbox,让发给Unit的ActorLocation消息重发
        unit.RemoveComponent<MailBoxComponent>(MailBoxComponent);

        // location加锁
        let oldInstanceId = unit.InstanceId;
        await LocationProxyComponent.Instance.Lock(unit.Id, unit.InstanceId);
        let response = await ActorMessageSenderComponent.Instance.Call(sceneInstanceId, request) as M2M_UnitTransferResponse;
        await LocationProxyComponent.Instance.UnLock(unit.Id, oldInstanceId, response.NewInstanceId);
        unit.Dispose();
    }

}